package edu.upc.sistemaventas.web;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UploadController {

	@RequestMapping(value = "/cargar_formulario", method = RequestMethod.GET)
	protected ModelAndView cargar_formulario(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		return new ModelAndView("upload");
	}

	@RequestMapping(value = "/subir_archivo", method = RequestMethod.POST)
	protected ModelAndView subir_archivo(@RequestParam("foto") MultipartFile file, WebRequest webRequest, Model model) throws Exception {

		String nombre = webRequest.getParameter("nom");
		System.out.println("Nombre: "+ nombre);
		
		
		String orgFileName = file.getOriginalFilename();
			
        String filePath = "d:/" + orgFileName;
        ModelMap modelMap = new ModelMap(); 
        
        File dest = new File(filePath);
        try {
        	System.out.println("Copiando el archivo a: " + dest);
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            modelMap.addAttribute("result", "File uploaded failed:" + orgFileName);
            return new ModelAndView("upload", modelMap);
                //return "File uploaded failed:" + orgFileName;
        } catch (IOException e) {
            e.printStackTrace();
            modelMap.addAttribute("result", "File uploaded failed:" + orgFileName);
            return new ModelAndView("upload", modelMap);
        }


        modelMap.addAttribute("result", "File uploaded " + orgFileName);

		return new ModelAndView("upload");
	}
}
